package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.IdCardUtil1;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param dto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto dto) {
        //判断老人是否已经入住,通过身份证号查询老人
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已入住");
        }

        //更新床位的状态 已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 保存或更新老人数据
        elder = insertOrUpdate(bed, dto.getCheckInElderDto());
        // 生成合同编号
        String contractNumber = "HT" + CodeGenerator.generateContractNumber();
        // 新增签约办理合同
        insertContract(contractNumber, elder, dto);
        // 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, dto);
        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), dto);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        // 查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        // 查询入住老人信息
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        int ageByIdCard = IdCardUtil1.getAgeByIdCard(elder.getIdCardNo());
        checkInElderVo.setAge(ageByIdCard);
        BeanUtils.copyProperties(elder, checkInElderVo);
        // 查询合同
        LambdaQueryWrapper<Contract> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(queryWrapper);
        // 查询入住配置信息
        LambdaQueryWrapper<CheckInConfig> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper1);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        //转换家属列表
        List<ElderFamilyVo> familyList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        //整合数据返回
        CheckInDetailVo detailVo = new CheckInDetailVo();
        detailVo.setContract(contract);
        detailVo.setElderFamilyVoList(familyList);
        detailVo.setCheckInConfigVo(checkInConfigVo);
        detailVo.setCheckInElderVo(checkInElderVo);
        return detailVo;
    }

    /**
     * 新增或更新老人信息
     *
     * @param bed
     * @param checkInElderDto
     * @return
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        //准备老人数据
        Elder elder = new Elder();
        //属性拷贝
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setStatus(1);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());

        //查询老人信息,(身份证号,状态不为1)
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderDb = elderMapper.selectOne(queryWrapper);
        if (ObjectUtils.isNotEmpty(elderDb)) {
            //更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        } else {
            //新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 新增签约办理合同
     *
     * @param contractNumber
     * @param elder
     * @param dto
     */
    private void insertContract(String contractNumber, Elder elder, CheckInApplyDto dto) {
        //准备签约办理合同数据
        Contract contract = new Contract();
        //属性拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNumber);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //状态,开始时间,结束时间
        //签约时间小于等于当前时间,合同生效中
        LocalDateTime checkInStartTime = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = dto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contract.setSignDate(dto.getCheckInContractDto().getSignDate());
        contractMapper.insert(contract);
    }

    /**
     * 新增入住信息
     *
     * @param elder
     * @param dto
     * @return
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto dto) {
        //准备入住信息数据
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());

        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }


    /**
     * 新增入住配置信息
     *
     * @param id
     * @param dto
     */
    private void insertCheckInConfig(Long id, CheckInApplyDto dto) {
        //准备入住配置数据
        CheckInConfig checkInConfig = new CheckInConfig();
        //属性拷贝
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(id);
        checkInConfig.setFeeStartDate(dto.getCheckInConfigDto().getStartDate());
        checkInConfig.setFeeEndDate(dto.getCheckInConfigDto().getEndDate());
        checkInConfigMapper.insert(checkInConfig);
    }


}
